package com.leostadyn.stackfarm.timestatistics.view.activity.employee;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.leostadyn.stackfarm.timestatistics.R;
import com.leostadyn.stackfarm.timestatistics.adapter.DialogProjectListAdapter;
import com.leostadyn.stackfarm.timestatistics.adapter.TimeRecordAdapter;
import com.leostadyn.stackfarm.timestatistics.model.bean.DetailProjectBean;
import com.leostadyn.stackfarm.timestatistics.model.bean.EmployeeBean;
import com.leostadyn.stackfarm.timestatistics.model.bean.StaffTimeRecordBean;
import com.leostadyn.stackfarm.timestatistics.net.api.AdminApi;
import com.leostadyn.stackfarm.timestatistics.net.base.OriginalSubscriber;
import com.leostadyn.stackfarm.timestatistics.net.base.ResponseThrowable;
import com.leostadyn.stackfarm.timestatistics.presenter.admin.FetchListPresenter;
import com.leostadyn.stackfarm.timestatistics.utils.DateUtils;
import com.leostadyn.stackfarm.timestatistics.utils.MyDialog;
import com.leostadyn.stackfarm.timestatistics.utils.TimeUtils;
import com.leostadyn.stackfarm.timestatistics.utils.ToastUtil;
import com.leostadyn.stackfarm.timestatistics.view.activity.MVPActivity;
import com.leostadyn.stackfarm.timestatistics.view.activity.setting.SettingActivity;
import com.leostadyn.stackfarm.timestatistics.view.vinterface.admin.IFetchListView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class EmployeeActivity extends MVPActivity<IFetchListView, FetchListPresenter> implements IFetchListView, View.OnClickListener {

    ImageView previousImg;
    ImageView nextImg;
    TextView dateTxt;
    ProgressBar progressBar;
    Button addBtn;
    Button commitBtn;
    RecyclerView rv_time;
    Date start;
    Date end;
    String startString;
    String endString;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");


    int offset = 0;
    SimpleDateFormat formatter = new SimpleDateFormat("MM.dd");
    StaffTimeRecordBean staffTimeRecordBean = new StaffTimeRecordBean();
    List<StaffTimeRecordBean.DataListBean> dataListBeanList = new ArrayList<>();
    StaffTimeRecordBean.InfosBean infosBean = new StaffTimeRecordBean.InfosBean();
    LinearLayout nodate;
    TimeRecordAdapter adapter;
    HashMap<String, String> map = new HashMap<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employee);
        initView();
        mPresenter.toTimeRecord(map, compositeDisposable);

    }

    void initView() {
        start = DateUtils.getDayOfWeek(Calendar.MONDAY, offset);
        end = DateUtils.getDayOfWeek(Calendar.SUNDAY, offset);

        String startString = formatter.format(start);
        String endString = formatter.format(end);

        previousImg = findViewById(R.id.img_previous);
        nextImg = findViewById(R.id.img_next);
        dateTxt = findViewById(R.id.txt_date);
        progressBar = findViewById(R.id.progressBar2);
        addBtn = findViewById(R.id.btn_add);
        commitBtn = findViewById(R.id.btn_commit);


        previousImg.setOnClickListener(this);
        nextImg.setOnClickListener(this);
        addBtn.setOnClickListener(this);
        commitBtn.setOnClickListener(this);


        dateTxt.setText("本周 " + startString + " ~ " + endString);
        previousImg.setOnClickListener(this);
        nextImg.setOnClickListener(this);

        TextView titleTxt = findViewById(R.id.nav_txt_title);
        titleTxt.setText("工时记录");

        findViewById(R.id.nav_img_back).setVisibility(View.GONE);
        findViewById(R.id.nav_btn_add).setVisibility(View.GONE);
        ImageView setting = findViewById(R.id.img_settings);
        setting.setOnClickListener(this);

        nodate = findViewById(R.id.layout_no_data);
        rv_time = findViewById(R.id.rv_timerecord);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_time.setLayoutManager(linearLayoutManager);

        startString = simpleDateFormat.format(start);
        endString = simpleDateFormat.format(end);
        map.put("beginDate", startString);
        map.put("endDate", endString);

    }


    @Override
    protected FetchListPresenter createPresenter() {
        return new FetchListPresenter();
    }

    @Override
    public void showWaiting() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void dismissWaiting() {
        progressBar.setVisibility(View.GONE);

    }

    @Override
    public void disconnected() {

    }

    @Override
    public void successProjectMessage(ArrayList<DetailProjectBean> projectList) {

    }

    @Override
    public void successEmployeeMessage(ArrayList<EmployeeBean> employeeList) {

    }

    @Override
    public void successMessage(ArrayList<DetailProjectBean> projectList, ArrayList<EmployeeBean> employeeList) {

    }

    @Override
    public void failureMessage(String s) {
        mPresenter.toTimeRecord(map, compositeDisposable);
    }

    @Override
    public void successTimeRecord(StaffTimeRecordBean staffTimeRecord) {

        this.staffTimeRecordBean = staffTimeRecord;
        if (staffTimeRecord != null)
            if (staffTimeRecord.getInfos() != null) {
                this.infosBean = staffTimeRecord.getInfos();
            }
        boolean flag = true;
        if (infosBean.getFirstInfo().equals("1")) {
            addBtn.setVisibility(View.GONE);
            commitBtn.setVisibility(View.GONE);
            findViewById(R.id.txt_notify).setVisibility(View.INVISIBLE);
            findViewById(R.id.warn_tv).setVisibility(View.INVISIBLE);
            flag = false;
        } else {
            addBtn.setVisibility(View.VISIBLE);
            commitBtn.setVisibility(View.VISIBLE);
            findViewById(R.id.txt_notify).setVisibility(View.VISIBLE);
            findViewById(R.id.warn_tv).setVisibility(View.VISIBLE);
            flag = true;
        }
        if (staffTimeRecordBean != null) {
            if (staffTimeRecordBean.getDataList() == null || staffTimeRecordBean.getDataList().size() == 0) {
                nodate.setVisibility(View.VISIBLE);
                rv_time.setVisibility(View.GONE);
                dataListBeanList = staffTimeRecordBean.getDataList();
                adapter = new TimeRecordAdapter(this, dataListBeanList, new TimeRecordAdapter.OnDeleteButtonClick() {
                    @Override
                    public void onBtnClicked(StaffTimeRecordBean.DataListBean dataListBean) {
                        dialogShow(dataListBean.getTimeSheetId());
                    }
                }, new TimeRecordAdapter.OnEditButtonClick() {
                    @Override
                    public void onEditButtonClick(StaffTimeRecordBean.DataListBean data) {
                        Intent intent = new Intent(EmployeeActivity.this, EmployeeEditActivity.class);
                        String s = TimeUtils.getTime2(data.getWorkDate());
                        startString = simpleDateFormat.format(start);
                        endString = simpleDateFormat.format(end);
                        intent.putExtra("createdTime", s);
                        intent.putExtra("startString", startString);
                        intent.putExtra("endString", endString);
                        intent.putExtra("code", data.getProjectCode());
                        intent.putExtra("name", data.getProjectName());
                        intent.putExtra("id", data.getProjectId());
                        intent.putExtra("workHour", data.getTaskTime());
                        intent.putExtra("timesheet", data.getTimeSheetId());
                        startActivity(intent);
                    }
                });
                adapter.setSwipe(flag);
                rv_time.setAdapter(adapter);
            } else {

                nodate.setVisibility(View.GONE);
                rv_time.setVisibility(View.VISIBLE);
                dataListBeanList = staffTimeRecordBean.getDataList();
                adapter = new TimeRecordAdapter(this, dataListBeanList, new TimeRecordAdapter.OnDeleteButtonClick() {
                    @Override
                    public void onBtnClicked(StaffTimeRecordBean.DataListBean dataListBean) {
                        dialogShow(dataListBean.getTimeSheetId());
                    }
                }, new TimeRecordAdapter.OnEditButtonClick() {
                    @Override
                    public void onEditButtonClick(StaffTimeRecordBean.DataListBean data) {
                        Intent intent = new Intent(EmployeeActivity.this, EmployeeEditActivity.class);
                        String s = TimeUtils.getTime2(data.getWorkDate());
                        startString = simpleDateFormat.format(start);
                        endString = simpleDateFormat.format(end);
                        intent.putExtra("createdTime", s);
                        intent.putExtra("startString", startString);
                        intent.putExtra("endString", endString);
                        intent.putExtra("code", data.getProjectCode());
                        intent.putExtra("name", data.getProjectName());
                        intent.putExtra("id", data.getProjectId());
                        intent.putExtra("workHour", data.getTaskTime());
                        intent.putExtra("timesheet", data.getTimeSheetId());
                        startActivity(intent);
                    }
                });
                adapter.setSwipe(flag);
                rv_time.setAdapter(adapter);

            }
        }

    }

    private void dialogShow(String id) {
        View view = getLayoutInflater().inflate(R.layout.layout_dialog, null);
        TextView dialog_delete = view.findViewById(R.id.dialog_delete);
        TextView dialog_cancel = view.findViewById(R.id.dialog_cancel);
        TextView dialog_theme = view.findViewById(R.id.dialog_theme);

        dialog_theme.setText("是否删除该工时？");

        final Dialog dialog = new MyDialog(this, 0, 0, view, R.style.DialogTheme);
        dialog.setCancelable(true);
        dialog.show();

        HashMap<String, String> deletemap = new HashMap<>();
        deletemap.put("id", id);
        dialog_delete.setOnClickListener(v -> {
            mPresenter.deleteTimeRecord(deletemap, compositeDisposable);
            dialog.dismiss();
            mPresenter.toTimeRecord(map, compositeDisposable);
        });
        dialog_cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });

    }

    @Override
    public void onClick(View v) {
        StringBuilder sb = new StringBuilder();

        switch (v.getId()) {
            case R.id.btn_add:
                startString = simpleDateFormat.format(start);
                endString = simpleDateFormat.format(end);
                Intent intent = new Intent(this, EmployeeAddActivity.class);
                intent.putExtra("date", startString);
                intent.putExtra("startString", startString);
                intent.putExtra("endString", endString);
                startActivity(intent);
                break;

            case R.id.img_settings:
                startActivity(new Intent(this, SettingActivity.class));
                break;

            case R.id.img_previous:
                offset--;
                if (offset == 0)
                    sb.append("本周");
                start = DateUtils.getDayOfWeek(Calendar.MONDAY, offset);
                end = DateUtils.getDayOfWeek(Calendar.SUNDAY, offset);
                startString = formatter.format(start);
                endString = formatter.format(end);
                sb.append(startString).append(" ~ ").append(endString);
                dateTxt.setText(sb.toString());
                startString = simpleDateFormat.format(start);
                endString = simpleDateFormat.format(end);

                map.clear();
                map.put("beginDate", startString);
                map.put("endDate", endString);
                mPresenter.toTimeRecord(map, compositeDisposable);
                break;

            case R.id.img_next:
                offset++;
                if (offset == 0)
                    sb.append("本周");
                if (offset <= 0) {
                    start = DateUtils.getDayOfWeek(Calendar.MONDAY, offset);
                    end = DateUtils.getDayOfWeek(Calendar.SUNDAY, offset);
                    startString = formatter.format(start);
                    endString = formatter.format(end);
                    sb.append(startString).append(" ~ ").append(endString);
                    dateTxt.setText(sb.toString());
                    startString = simpleDateFormat.format(start);
                    endString = simpleDateFormat.format(end);
                    map.clear();
                    map.put("beginDate", startString);
                    map.put("endDate", endString);
                    mPresenter.toTimeRecord(map, compositeDisposable);
                } else {
                    ToastUtil.show(this, "下周还没到呢！");
                    offset--;
                }
                break;

            case R.id.btn_commit:
                commitRecord(dataListBeanList);

            default:
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.toTimeRecord(map, compositeDisposable);
    }

    public void commitRecord(List<StaffTimeRecordBean.DataListBean> dataListBeanList) {
        String startString;
        String endString;
        start = DateUtils.getDayOfWeek(Calendar.MONDAY, offset);
        end = DateUtils.getDayOfWeek(Calendar.SUNDAY, offset);
        startString = TimeUtils.getTime2(start);
        endString = TimeUtils.getTime2(end);

        View view = getLayoutInflater().inflate(R.layout.layout_commit, null);
        TextView confirm = view.findViewById(R.id.dialog_ok);
        TextView cancel = view.findViewById(R.id.dialog_cancel);
        TextView time = view.findViewById(R.id.dialog_time_title);
        TextView dayCounts = view.findViewById(R.id.dialog_days);
        RecyclerView projectRv = view.findViewById(R.id.dialog_project_list);
        DialogProjectListAdapter adapter;

        time.setText("时间：" + startString + "~" + endString);

        adapter = new DialogProjectListAdapter(this, dataListBeanList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        projectRv.setLayoutManager(linearLayoutManager);
        projectRv.setAdapter(adapter);
        dayCounts.setText(adapter.getCount() + "天");

        final Dialog dialog = new MyDialog(this, 0, 0, view, R.style.DialogTheme);
        dialog.setCancelable(true);
        dialog.show();
        String ids = "";
        int flag = 0;
        for (StaffTimeRecordBean.DataListBean data : dataListBeanList) {
            if (flag == 0) {
                ids += data.getTimeSheetId();
            } else {
                ids = ids + "-" + data.getTimeSheetId();
            }
            flag++;
        }
        String finalIds = ids;
        confirm.setOnClickListener(v -> {
            AdminApi.getInstance().submitTimeRecord(finalIds).subscribe(new OriginalSubscriber<String>(compositeDisposable) {
                @Override
                public void onError(ResponseThrowable e) {
                    ToastUtil.show(EmployeeActivity.this, "提交失败");

                }

                @Override
                public void onNext(String s, String msg) {
                    ToastUtil.show(EmployeeActivity.this, "提交成功");
                    mPresenter.toTimeRecord(map, compositeDisposable);

                }

            });
            dialog.dismiss();

        });

        cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });

    }
}


